import { HttpException, Injectable, Req } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { UserEntity } from "./entity/user.entity";
import { Connection, Repository } from "typeorm";
import { AccountEntity } from "./entity/account.entity";
import { UsersRegisterDto } from "./dto/users-register.dto";
import { format } from "date-fns";
import { UserAlreadyExistsException } from "../../common/constant/Exception/user-already-exists.exception";
import { CaptchaFailException } from "../../common/constant/Exception/captcha-fail.exception";
import { ErrorInputException } from "../../common/constant/Exception/error-input.exception";

@Injectable()
export class UsersService {
  constructor(
    private connection: Connection,
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
    @InjectRepository(AccountEntity)
    private readonly accountRepository: Repository<AccountEntity>
  ) {
  }

  //用户创建
  async usersCreate(dto: UsersRegisterDto, @Req() request) {
    const queryRunner = this.connection.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();
    try {
      if (!dto || dto.captcha || !dto.password || !dto.account || !dto.nickname) {
        //查看验证码是否正确
        const flag = await request.session.captcha === dto.captcha;
        if (flag) {
          request.session = null;
          //初始化账户仓库
          const accountRepository = this.connection.getRepository(AccountEntity);
          const account = new AccountEntity();
          account.account = dto.account;
          //查看当前账户是已经存在
          const accountIsExist = await this.accountFind(account);
          if (!accountIsExist) {
            account.password = dto.password;
            //新增账户
            const accountRes = await accountRepository.save(account);

            //新增用户
            const user = new UserEntity();
            user.aId = accountRes.id;
            user.status = 2;
            user.createTime = format(new Date(), "yyyy-MM-dd HH:mm:ss");
            user.type = "domestic";
            user.nickname = dto.nickname;
            const userRes = await queryRunner.manager.save(user);
            await queryRunner.commitTransaction();
            return userRes;

          } else {
            throw new UserAlreadyExistsException();
          }
        } else {
          throw new CaptchaFailException();
        }
      } else {
        throw new ErrorInputException();
      }
    } catch (e) {
      await queryRunner.rollbackTransaction();
      throw new HttpException(e.message, e.status);
    } finally {
      await queryRunner.release();
    }
  }


  //查找用户
  async usersFind(user: UserEntity) {
    const userRepository = this.connection.getRepository(UserEntity);
    return await userRepository.findOne({ where: user });
  }

  // 查找账户
  async accountFind(account: AccountEntity) {
    const accountRepository = this.connection.getRepository(AccountEntity);
    return await accountRepository.findOne({ where: account });
  }

//  返回账户名
  async getAccount(user) {
    const accountRes = await this.accountRepository.findOne({ where: { id: user.aId } });
    return accountRes.account;
  }

  //获取账户对象
  async updateUser(dto, user) {
    console.log(user.id);
    console.log(dto);
    await this.userRepository.update({ id: user.id }, dto);
    return await this.userRepository.findOne({ where: { id: user.id } });
  }

  async passwordUpdate(dto, user) {
    if (dto.confirmPassword === dto.newPassword) {
      const updateUser = await this.userRepository.findOne({ where: { id: user.id } });
      return await this.accountRepository.update({ id: updateUser.aId }, { password: dto.confirmPassword });
    }else {
      throw new HttpException("两次密码输入不一样", 401);
    }
  }
}

